package patterns;

import java.util.Observable;
import java.util.Observer;

/**
 * 观察者模式
 */
public class LearnObserver {
    public static void main(String[] args) {
        // 创建订阅号
        ChatAccount account = new ChatAccount("Java学习之路");
        // 创建用户
        User user1 = new User("小明");
        User user2 = new User("小红");
        // 用户订阅订阅号
        account.addObserver(user1);
        account.addObserver(user2);
        // 订阅号推送新消息
        account.publishMessage("欢迎关注Java学习之路！今日主题：观察者模式");
    }
}

class User implements Observer {
    private String username;

    public User(String username) {
        this.username = username;
    }

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof ChatAccount) {
            System.out.println("用户 " + username + " 收到来自订阅号 [" + ((ChatAccount) o).getName() + "] 的新消息：" + arg);
        }
    }
}

class ChatAccount extends Observable {
    private String name;

    public ChatAccount(String name) {
        this.name = name;
    }

    public void publishMessage(String message) {
        setChanged();
        notifyObservers(message);
    }

    public String getName() {
        return name;
    }
}